<!-- 商品发布 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="formData.name"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入商品名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品分类" prop="categoryId">
      <el-cascader
        v-model="formData.categoryId"
        :options="categoryList"
        :props="defaultProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择商品分类"
      />
    </el-form-item>
    <el-form-item label="商品品牌" prop="brandId">
      <el-select v-model="formData.brandId" class="w-80!" placeholder="请选择商品品牌" :disabled="isDetail">
        <el-option
          v-for="item in brandList"
          :key="item.id"
          :label="item.name"
          :value="item.id as number"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="商品关键字" prop="keyword">
      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />
    </el-form-item>
    <el-form-item label="商品类型" prop="productType">
      <el-select v-model="formData.productType" placeholder="请选择商品类型" :disabled="isDetail" class="w-80!">
        <el-option label="次卡" value="TIME_CARD" />
      </el-select>
    </el-form-item>
    <el-form-item label="使用次数" prop="useTime">
      <el-input-number v-model="formData.useTime" :min="0" placeholder="请输入使用次数" class="w-80!" :disabled="isDetail" />
    </el-form-item>
    <el-form-item label="套餐搭配" prop="productPacketItems">
      <el-button @click="addPacketItem" :disabled="isDetail">添加套餐项</el-button>
      <el-table :data="productPacketItems" style="width: 100%; margin-top: 10px;">
        <el-table-column label="单品" prop="itemId" min-width="200">
          <template #default="{ row }">
            <el-select
              v-model="row.itemId"
              placeholder="请选择产品"
              filterable
              :disabled="isDetail"
              @visible-change="handleSingleItemSelectVisibleChange"
              @change="handlePacketItemChange(row)"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
              <!-- Loading Indicator -->
              <el-option
                v-if="productLoading"
                disabled
                value="__loading__"
                label="加载中..."
                style="text-align: center; color: #999;"
              />
              <el-option
                v-if="!productLoading && productList.length === 0"
                disabled
                value="__nodata__"
                label="暂无数据"
                style="text-align: center; color: #999;"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量设置" prop="num" min-width="240">
          <template #default="{ row }">
            <div class="flex gap-2">
              <el-input-number 
                v-model="row.num" 
                :min="1" 
                placeholder="数量" 
                :disabled="isDetail"
                style="width: 120px;"
              />
              <el-select 
                v-model="row.unitId" 
                placeholder="选择单位" 
                :disabled="isDetail"
                style="width: 120px;"
                @change="handleUnitChange(row)"
              >
                <el-option
                  v-for="unit in getAvailableUnits(row.itemId)"
                  :key="unit.id"
                  :label="unit.name"
                  :value="unit.id"
                />
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" v-if="!isDetail">
          <template #default="{ $index }">
            <el-button type="danger" link @click="removePacketItem($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="商品简介" prop="introduction">
      <el-input
        v-model="formData.introduction"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="128"
        placeholder="请输入商品简介"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="商品标签" prop="tags">
      <TagSelector
        v-model="formData.tags"
        placeholder="点击选择商品标签"
        :disabled="isDetail"
        class="w-80!"
      />
    </el-form-item>
    <el-form-item label="商品封面图" prop="picUrl">
      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
    </el-form-item>
    <el-form-item label="商品轮播图" prop="sliderPicUrls">
      <UploadImgs v-model="formData.sliderPicUrls!" :disabled="isDetail" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { PropType, reactive, ref, watch, unref, onMounted, nextTick } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/localLife/spu'
import * as ProductCategoryApi from '@/api/localLife/category'
import { CategoryVO } from '@/api/localLife/category'
import * as SingleItemApi from '@/api/localLife/singleItem'
import * as ProductBrandApi from '@/api/mall/product/brand'
import { BrandVO } from '@/api/mall/product/brand'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import TagSelector from '@/components/TagSelector/index.vue'

defineOptions({ name: 'LocalLifeSpuInfoForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => ({})
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗

const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图 - Initialized as empty array directly
  introduction: '', // 商品简介
  brandId: undefined, // 商品品牌 - Keep field, but remove UI
  productType: 'TIME_CARD', // 商品类型 default
  useTime: 0, // 使用次数 default
  productPacket: '', // This will hold the JSON string from productPacketItems
  tags: [] // 商品标签
})

const productPacketItems = ref<any[]>([]) // Initialize empty, will be populated from productPacket string

// 产品列表数据
const productList = ref<ProductVO[]>([])
const productLoading = ref(false)

// Re-add brandList
const brandList = ref<BrandVO[]>([])

const rules = reactive({
  name: [required],
  categoryId: [required],
  keyword: [required],
  introduction: [required],
  picUrl: [required],
  sliderPicUrls: [required],
  productType: [required],
  useTime: [required],
  brandId: [required] // Re-add rule for brandId
})

const addPacketItem = () => {
  productPacketItems.value.push({ 
    itemId: undefined, 
    num: 1, 
    unitId: undefined,
    unitName: '',
    isMinUnit: false,
    title: '' 
  })
}

const removePacketItem = (index: number) => {
  productPacketItems.value.splice(index, 1)
}

/** Handle change event when a single item is selected in the packet table */
const handlePacketItemChange = (row: any) => {
  const selectedItem = productList.value.find(item => item.id === row.itemId)
  if (selectedItem) {
    row.title = selectedItem.name
    // 清空单位选择，让用户重新选择
    row.unitId = undefined
    row.unitName = ''
    row.isMinUnit = false
  } else {
    row.title = ''
    row.unitId = undefined
    row.unitName = ''
    row.isMinUnit = false
  }
}

/** 处理单位变化 */
const handleUnitChange = (row: any) => {
  const availableUnits = getAvailableUnits(row.itemId)
  const selectedUnit = availableUnits.find(unit => unit.id === row.unitId)
  if (selectedUnit) {
    // 设置单位名称
    row.unitName = selectedUnit.name
    // 设置是否为最小单位
    row.isMinUnit = selectedUnit.isMinUnit
  }
}

/** 获取可用单位列表 - 根据选中的产品ID获取相关单位 */
const getAvailableUnits = (itemId: number) => {
  if (!itemId) return []
  
  const selectedProduct = productList.value.find(item => item.id === itemId)
  if (!selectedProduct) return []
  
  const units = []
  
  // 添加标准单位
  if (selectedProduct.unitId && selectedProduct.unitName) {
    units.push({
      id: selectedProduct.unitId,
      name: selectedProduct.unitName,
      isMinUnit: false
    })
  }
  
  // 添加最小单位
  if (selectedProduct.minUnitId && selectedProduct.minUnitName) {
    units.push({
      id: selectedProduct.minUnitId,
      name: selectedProduct.minUnitName,
      isMinUnit: true
    })
  }
  
  return units
}

/** 获取ERP产品列表 */
const getProductList = async () => {
  productLoading.value = true
  try {
    // 调用ERP产品分页接口，写死第一页100条
    const data = await ProductApi.getProductPage({
      pageNo: 1,
      pageSize: 100
    })
    productList.value = data.list || []
  } catch (error) {
    console.error('获取产品列表失败:', error)
    message.error('获取产品列表失败')
  } finally {
    productLoading.value = false
  }
}

/** 处理下拉框显示变化 */
const handleSingleItemSelectVisibleChange = (visible: boolean) => {
  if (visible && productList.value.length === 0) {
    // 当下拉框显示且产品列表为空时，加载产品列表
    getProductList()
  }
}

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    // Ensure sliderPicUrls is always an array before copying
    if (data.sliderPicUrls === undefined) {
      data.sliderPicUrls = []
    }
    copyValueToTarget(formData, data)
    if (data.productPacket) {
      try {
        const parsedPacket = JSON.parse(data.productPacket)
        if (Array.isArray(parsedPacket)) {
          productPacketItems.value = parsedPacket
        } else {
          console.warn('Parsed productPacket is not an array:', parsedPacket)
          productPacketItems.value = [] // Reset if invalid structure
        }
      } catch (e) {
        console.error('Failed to parse productPacket:', e)
        message.error('解析商品套餐数据失败')
        productPacketItems.value = [] // Reset on error
      }
    } else {
      if (productPacketItems.value.length === 0) {
        addPacketItem()
      }
    }
  },
  {
    immediate: true,
    deep: true // Deep watch needed for propFormData changes
  }
)

const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef.value) return

  // ===== Add check for empty product packet array =====
  if (productPacketItems.value.length === 0) {
    message.error('【基础设置】套餐搭配不能为空，请至少添加一项')
    emit('update:activeName', 'info')
    throw new Error('Product packet is required and cannot be empty')
  }
  // ===== End check =====

  // Validate items in productPacketItems before main validation
  for (const item of productPacketItems.value) {
    if (!item.itemId) {
      message.error('【基础设置】商品套餐中存在未选择的单品')
      emit('update:activeName', 'info')
      throw new Error('Product packet item missing itemId')
    }
    if (!item.num || item.num < 1) {
      message.error('【基础设置】商品套餐中存在数量不合法的项')
      emit('update:activeName', 'info')
      throw new Error('Product packet item invalid num')
    }
  }

  try {
    await unref(formRef)?.validate()
    try {
      formData.productPacket = JSON.stringify(productPacketItems.value)
    } catch (e) {
       console.error('Failed to stringify productPacketItems:', e)
       message.error('转换商品套餐数据失败')
       throw e
    }

    Object.assign(props.propFormData, formData)

  } catch (e) {
    if (!(e instanceof Error && e.message.startsWith('Product packet'))) {
      message.error('【基础设置】不完善，请填写相关信息')
    }
    emit('update:activeName', 'info')
    throw e
  }
}
defineExpose({ validate })

/** 初始化 */
const categoryList = ref<CategoryVO[]>([]) // 商品分类树
onMounted(async () => {
  // 获得分类树
  const categoryData = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(categoryData, 'id')
  // Re-fetch brand list
  brandList.value = await ProductBrandApi.getSimpleBrandList()
  // 获取产品列表
  await getProductList()
  // Initialize with one empty packet item if creating new and list is empty
  if (!props.propFormData?.id && productPacketItems.value.length === 0) {
      addPacketItem()
  }
})
</script>
